package com.maltys.greedy;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/">买卖股票的最佳时机II</a>
 */
public class BestTimeToBuyAndSellStockII {
    public static void main(String[] args) {
        BestTimeToBuyAndSellStockII sellStockII = new BestTimeToBuyAndSellStockII();
        int profit = sellStockII.maxProfit(new int[]{7, 1, 5, 3, 6, 4});
        int profit2 = sellStockII.maxProfit2(new int[]{7, 1, 5, 3, 6, 4});
        System.out.println(profit);
        System.out.println(profit2);
    }

    /**
     * 贪心的解法
     */
    public int maxProfit(int[] prices) {
        int sum = 0;
        for (int i = 1; i < prices.length; i++) {
            sum += Math.max(prices[i] - prices[i - 1], 0);
        }
        return sum;
    }

    /**
     * 动态规划的解法
     */
    public int maxProfit2(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][1] - prices[i], dp[i - 1][0]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[dp.length - 1][1];
    }
}
